/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ws.service;

import entidade.persistencia.Permissao;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import entidade.persistencia.TipoUsuario;
import java.util.List;
import ws.converter.PermissaoConverter;

/**
 *
 * @author victorinox
 */

public class PermissaoResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;
  
    /** Creates a new instance of PermissaoResource */
    public PermissaoResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * Get method for retrieving an instance of Permissao identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of PermissaoConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public PermissaoConverter get(@QueryParam("expandLevel")
    @DefaultValue("1")
    int expandLevel) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new PermissaoConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

    /**
     * Put method for updating an instance of Permissao identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an PermissaoConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(PermissaoConverter data) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            EntityManager em = persistenceSvc.getEntityManager();
            updateEntity(getEntity(), data.resolveEntity(em));
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Delete method for deleting an instance of Permissao identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            deleteEntity(getEntity());
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Returns an instance of Permissao identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Permissao
     */
    protected Permissao getEntity() {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        try {
            return (Permissao) em.createQuery("SELECT e FROM Permissao e where e.permissaoId = :permissaoId").setParameter("permissaoId", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    protected Permissao updateEntity(Permissao entity, Permissao newEntity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        List<TipoUsuario> tipoUsuarioCollection = entity.getTipoUsuarioCollection();
        List<TipoUsuario> tipoUsuarioCollectionNew = newEntity.getTipoUsuarioCollection();
        entity = em.merge(newEntity);
        for (TipoUsuario value : tipoUsuarioCollection) {
            if (!tipoUsuarioCollectionNew.contains(value)) {
                value.getPermissaoCollection().remove(entity);
            }
        }
        for (TipoUsuario value : tipoUsuarioCollectionNew) {
            if (!tipoUsuarioCollection.contains(value)) {
                value.getPermissaoCollection().add(entity);
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    protected void deleteEntity(Permissao entity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        for (TipoUsuario value : entity.getTipoUsuarioCollection()) {
            value.getPermissaoCollection().remove(entity);
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of TipoUsuarioesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of TipoUsuarioesResource
     */
    @Path("tipoUsuarioCollection/")
    public TipoUsuarioesResource getTipoUsuarioCollectionResource() {
        TipoUsuarioCollectionResourceSub resource = resourceContext.getResource(TipoUsuarioCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    public static class TipoUsuarioCollectionResourceSub extends TipoUsuarioesResource {

        private Permissao parent;

        public void setParent(Permissao parent) {
            this.parent = parent;
        }

        @Override
        protected List<TipoUsuario> getEntities(int start, int max, String query) {
            List<TipoUsuario> result = new java.util.ArrayList<TipoUsuario>();
            int index = 0;
            for (TipoUsuario e : parent.getTipoUsuarioCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
